package com.ruoyi.project.er.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.er.domain.*;
import com.ruoyi.project.er.enums.PaeaErrorReplyStatus;
import com.ruoyi.project.er.enums.PaeaErrorStatus;
import com.ruoyi.project.er.mapper.PaeaErErrorMapper;
import com.ruoyi.project.er.mapper.PaeaErErrorPointRelMapper;
import com.ruoyi.project.er.service.*;
import com.ruoyi.project.wf.domain.*;
import com.ruoyi.project.wf.service.IWfProcessActRoleRelService;
import com.ruoyi.project.wf.service.IWfProcessActService;
import com.ruoyi.project.wf.service.IWfProcessInstService;
import com.ruoyi.project.wf.service.IWfWorkItemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 督办查询Service业务层处理
 *
 * @author XQ.XU
 * @date 2020-03-22
 */
@Service
public class PaeaErErrorRegisterServiceImpl extends ServiceImpl<PaeaErErrorMapper, PaeaErError> implements IPaeaErErrorRegisterService
{
    @Resource
    private PaeaErErrorMapper paeaErErrorMapper;
    @Resource
    private PaeaErErrorPointRelMapper paeaErErrorPointRelMapper;
    @Resource
    private IPaeaErErrorPointRelService paeaErErrorPointRelService;
    @Resource
    private IPaeaErPointService paeaErPointService;
    @Resource
    private IPaeaErTypeService paeaErTypeService;
    @Resource
    private IWfProcessInstService wfProcessInstService;
    @Resource
    private IWfWorkItemService wfWorkItemService;
    @Resource
    private IWfProcessActService wfProcessActService;
    @Resource
    private IPaeaErErrorInstRelService paeaErErrorInstRelService;
    @Resource
    private IWfProcessActRoleRelService wfProcessActRoleRelService;
    @Resource
    private IPaeaErTypePointRelService paeaErTypePointRelService;
    @Resource
    private IPaeaErGradeService paeaErGradeService;
    @Resource
    private IPaeaErErrorService paeaErErrorService;
    @Override
    public int deletePaeaErError(@NotNull List<String> errIds) {
        return paeaErErrorService.deletePaeaErError(errIds);
    }
    @Override
    public int registerError(PaeaErError paeaErError) {
        //TODO：差错信息补全
        paeaErError.setAuTypeName("");
        paeaErError.setOrgName("");
        paeaErError.setOrgPath("");
        paeaErError.setAuditOrg("");
        paeaErError.setTellerName("");

        paeaErError.setAuditOrg(ShiroUtils.getSysUser().getDeptId());
        paeaErError.setErrRegOper(ShiroUtils.getUserId());
        paeaErError.setNotifyDate(new Date(System.currentTimeMillis()));
        paeaErError.setNotifyNum(1);
        paeaErError.setReplyFlag(PaeaErrorReplyStatus.未回复.getValue());
        paeaErError.setCorrectOvertime(0);
        paeaErError.setTimes(1);
        paeaErError.setDateY(DateUtils.parseDateToYear(paeaErError.getTrDate()));
        paeaErError.setDateM(DateUtils.parseDateToMonth(paeaErError.getTrDate()));
        paeaErError.setDateQ(DateUtils.parseDateToQuarter(paeaErError.getTrDate()));
        paeaErError.setCode(getNewErrorCode(paeaErError));
        //流水标志
        if(StringUtils.isNotEmpty(paeaErError.getTradeId())
         ||StringUtils.isNotEmpty(paeaErError.getVchNo())
        ){
            paeaErError.setVchFlag("1");
        }else{
            paeaErError.setVchFlag("0");
        }

        this.saveOrUpdate(paeaErError);
        //风险点信息
        List<PaeaErErrorPointRel> erPointRels = new ArrayList<PaeaErErrorPointRel>();
        String lastPointId="";
        String paeaErTypeId="";
        for(String pointId:paeaErError.getPaeaErPointIds()){
            if(pointId.startsWith("EPI")){
                paeaErTypeId=pointId.substring(3);
            }else {
                PaeaErErrorPointRel rel = new PaeaErErrorPointRel();
                lastPointId = pointId;
                rel.setErrId(paeaErError.getId());
                rel.setErrPointId(pointId);
                rel.setErrTypeId(paeaErTypeId);
                erPointRels.add(rel);
            }
        }

        //更新差错类型等级
        PaeaErPoint point=paeaErPointService.selectPaeaErPointById(lastPointId);
        PaeaErType paeaErType =paeaErTypeService.selectPaeaErTypeById(paeaErTypeId);
        //PaeaErGrade paeaErGrade=paeaErGradeService.selectPaeaErGradeById(point.getGradeId());
        //PaeaErGrade paeaErGrade=paeaErType.getPaeaErGrade();
        paeaErError.setErrTypeId(paeaErTypeId);
        paeaErError.setErrTitle(paeaErType.getTypeName());

        //TODO:类型等级还是风险点等级？
        paeaErError.setErrGrade(point.getGradeId());
        this.saveOrUpdate(paeaErError);
        paeaErErrorPointRelService.deletePaeaErErrorPointRelByErrId(paeaErError.getId());
        paeaErErrorPointRelService.saveBatch(erPointRels);
        //WF 流程信息
        // 如果是提交，直接提交到下一流程
        if (true) {
            WfProcessDef wfProcessDef=paeaErType.getWfProcessDef();
            // 启动流程
            if (wfProcessDef == null ) {
                return 0;
               // throw new Exception("差错类型【" + paeaErType.getCode() + "-"+ paeaErType.getTypeName() + "】没有配置处理流程");
            }
            WfProcessInst wfProcessInst = wfProcessInstService.createWfProcessInst(wfProcessDef);
            // 缺省情况要提交第一个开始的节点
            WfWorkItem currentWorkItem = wfWorkItemService.submitStartWfWorkItem(wfProcessInst,paeaErError.getTrDate());
            // 保存差错和流程实例的关系
           if (paeaErError != null && wfProcessInst != null) {
               WfProcessActRoleRel wfProcAct2SmRole=new WfProcessActRoleRel();
               wfProcAct2SmRole.setProcActId(currentWorkItem.getProcActId());
               List<WfProcessActRoleRel> wfProcAct2SmRoles= wfProcessActRoleRelService.selectWfProcessActRoleRelList(wfProcAct2SmRole);
                for (WfProcessActRoleRel act2Role: wfProcAct2SmRoles) {
                    paeaErError.setCurRoleId(act2Role.getRoleCode());
                    paeaErError.setResponsibleOper("-1");
                    paeaErError.setAcquiredTime(null);
                    paeaErError.setAcquiredStatus(1);
                    break;
                }
                paeaErError.setErrState(currentWorkItem.getName());
                paeaErError.setCurWorkitemId(currentWorkItem.getId());
                paeaErError.setErrStatus(PaeaErrorStatus.Published.getValue());
                this.saveOrUpdate(paeaErError);
                PaeaErErrorInstRel eIRel = new PaeaErErrorInstRel();
               eIRel.setErrId(paeaErError.getId());
               eIRel.setProcInstId(wfProcessInst.getId());
                paeaErErrorInstRelService.saveOrUpdate(eIRel);
            }
            //TODO:日志 更新一条差错统计信息
            //PaeaReportError reportError = createPaeaReportError(paeaErError);
            //servicePaeaReportErrorImpl.writeStatPaeaReportError(reportError);

        } else {
            paeaErError.setErrStatus(PaeaErrorStatus.Registered.getValue());
            // 先插入一条差错记录
            this.saveOrUpdate(paeaErError);
        }
        return 1;
    }


    private String getNewErrorCode(PaeaErError paeaErError ) {
        String prefix = "";
        String hql = "";
        Object[] values = null;
        prefix=paeaErError.getDateY()+"-"+paeaErError.getOrgId()+"-";
        String maxCode=this.paeaErErrorMapper.selectMaxCodeByError(paeaErError);
        if(StringUtils.isEmpty(maxCode)){
            return prefix + "00001";
        }
        if (maxCode.indexOf(prefix) == 0) {
            maxCode = maxCode.substring(prefix.length());
        }
        int seqNo = Integer.valueOf(maxCode.length() > 5 ? maxCode.substring(maxCode.length() - 5) : maxCode);
        if (seqNo > 99999) {
            seqNo = 1;
        }
        return prefix + String.format("%05d", seqNo + 1);
    }
}
